<template>
  <view v-if="detailInfo" class="page uni-bg-white">
    <uni-nav-bar ref="navBar" class="absolute" style="z-index:10;" statusBar :border="false" backgroundColor="transparent" @clickLeft="goBack">
      <template v-slot:left>
        <image class="size-32" src="@/static/svg/icon-back.svg" />
      </template>
    </uni-nav-bar>
    <scroll-view class="container" :style="`height:calc(100% - 52px - ${safeAreaBottom}px);`" scroll-y>
      <uni-swiper-dot class="" :info="photos" :current="swiperDotIndex" :dotsStyles="{bottom:8}">
        <swiper class="swiper-box" autoplay circular :interval="2000" @change="swiperChange" :current="swiperDotIndex">
          <swiper-item v-for="(item, index) in photos" :key="index">
            <view class="swiper-item">
              <video v-if="isVideoFile(item)" class="h-full" :src="item"></video>
              <image v-else class="h-full" mode="aspectFill" :src="item"></image>
              <!-- <uni-notice-bar class="notice-bar fs-12 font-normal" scrollable :speed="50"
								background-color="rgba(0, 0, 0, 0.30)" color="#FFF"
								:text="detailInfo.activeState===4 ? '活动已结束' : `活动将于${formatEndTime(detailInfo.endTime)}后结束`" /> -->
            </view>
            <view v-if="detailInfo.activeState===4||(!isLink && detailInfo.remainStock===0)" class="swiper-stamp">
              <image v-if="detailInfo.activeState===4" class="swiper-stamp-img" src="@/static/svg/activity/stamp-finished.svg"></image>
              <image v-else-if="detailInfo.remainStock===0" class="swiper-stamp-img" src="@/static/svg/activity/stamp-snapped-up.svg"></image>
              <!-- <image class="swiper-stamp-img" src="@/static/svg/activity/stamp-sold-out.svg"></image> -->
            </view>
          </swiper-item>
        </swiper>
      </uni-swiper-dot>
      <danmu v-if="detailInfo.activeState===3" class="danmu" text="下单了+1"></danmu>

      <view class="flex justify-between top px-16 pt-12 pb-12 radius-8 radius-bl-0-i radius-br-0-i relative z-1" style="background: linear-gradient(to bottom, #FA4543, #FD6E4B); margin-top: -8px;">
        <view>
          <text class="fs-21 font-semibold leading-22 mb-4 mr-8 block">
            <text class="fs-14 font-normal">¥</text>
            {{ numberFormat(detailInfo.activePrice) }}
          </text>
          <view class="flex">
            <text class="fs-14 font-normal leading-22 text-throughline mr-8">
              ¥{{ numberFormat(detailInfo.originPrice) }}
            </text>
            <tag v-if="detailInfo.userPointsAmt" class="block" custom-class="radius-12 color-primary-i px-12">
              下单得{{ detailInfo.userPointsAmt }}积分
            </tag>
          </view>
        </view>
        <view class="">
          <view class="flex justify-end mb-4">
            <text>&nbsp;</text>
          </view>
          <view class="fs-12 font-normal leading-22 flex item-center">
            已售
            <image class="w-12 h-12" src="https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/pintuan-thunder.png"></image>
            {{ detailInfo.buyNum+ (detailInfo.virtualSaleNum?detailInfo.virtualSaleNum:0) }}份
          </view>
        </view>
      </view>

      <view class="flex-col radius-8 relative z-1" style="margin-top: -8px;">
        <view class="uni-bg-white radius-12 px-16 py-16 mb-8">
          <view>
            <!-- <sign-up-tag v-if="isSignUp" class="mr-5" /> -->
            <text class="text-color-regular fs-14 font-semibold leading-22 align-middle">{{detailInfo.activeTitle}}</text>
          </view>
          <!-- <view class="flex justify-between mt-8">
						<view class="flex item-center">
							<text class="price mr-8"><text class="symbol">¥</text>{{numberFormat(detailInfo.activePrice)}}</text>
							<text class="old-price"><text class="symbol">¥</text>{{numberFormat(detailInfo.originPrice)}}</text>
						</view>
						<view v-if="!isSignUp && detailInfo.remainStock" class="stoce">
							<image class="w-12 h-12 mr-4" src="@/static/svg/activity/icon-ticket.svg"></image>
							<text>剩{{detailInfo.remainStock}}份</text>
						</view>
					</view> -->
          <view class="mt-8 mb-12">
            <newcomer-coupon-tag v-if="detailInfo.activeRedPacket" class="mr-8" :price="detailInfo.activeRedPacket.firstRedPacketAmt" @click="showRedPacket" />
            <template v-if="detailInfo.activeDiscount && detailInfo.activeDiscount.length">
              <full-discount-tag v-for="(item,index) in detailInfo.activeDiscount" :key="index" :data="item" class="mr-8" />
            </template>
          </view>
          <view v-if="isSignUp && detailInfo.activeStepPrices && detailInfo.activeStepPrices.length" class="mb-12">
            <sign-up-number-tag v-for="(item,index) in detailInfo.activeStepPrices" :key="index" :number="item.enrollNum" :price="numberFormat(detailInfo.activePrice - item.enrollPrice,2)" :type="2" class="mr-8" />
          </view>
          <view class="flex justify-between item-center mt-8">
            <!-- <view class="flex flex-col">
							<text class="fs-12 text-color-hint">{{formatBeginTime(detailInfo.releaseTime)}} 发布</text>
							<text v-if="detailInfo.browseNum" class="viewer-info">{{detailInfo.browseNum}}人查看</text>
							<text v-if="detailInfo.browseNum && detailInfo.buyNum" class="viewer-info">｜</text>
							<text v-if="detailInfo.buyNum" class="viewer-info">{{detailInfo.buyNum}}次购买</text>
						</view> -->
            <location-info :info="detailInfo.address"></location-info>
            <!-- 活动状态: 1-未发布，2-未开始 隐藏收藏按钮 -->
            <collect-button v-if="![1,2].includes(detailInfo.activeState)" :userId="userStore.userInfo && userStore.userInfo.id" :activeId="detailInfo.id" :collectState="detailInfo.collectState" @onStateChange="toRefresh" />
          </view>
          <view class="flex flex-wrap mt-8">
            <view class="bg-primary cf fs-12 radius-4 mx-4 px-6 py-2">过期退</view>
            <view v-if="detailInfo.autoRefundEnabled" class="bg-primary cf fs-12 radius-4 mx-4 px-6 py-2">随时退</view>
          </view>
        </view>
        <sign-up-people v-if="isSignUp && detailInfo.enrolledNum" :enrolledNum="detailInfo.enrolledNum" :enrolledAvatars="detailInfo.enrolledAvatars" class="mt-8 mx-16" />
        <promotion-interest v-if="detailInfo.agentState===2" class="mt-8 mx-16" :commissionAmt="detailInfo.commissionAmt" :otherEquity="detailInfo.otherEquity" :commissionRate="detailInfo.commissionRate" :defaultCommissionType="detailInfo.defaultCommissionType" :activePrice="detailInfo.activePrice" />
        <view v-if="detailInfo.activeGoods && detailInfo.activeGoods.length" class="mb-16 mx-16">
          <view class="tabs">
            <view class="tab-item" :class="activeTab===0?'active':''" @click="activeTab=0">
              <image v-if="activeTab===0" mode="widthFix" class="absolute h-full" style="top:-8px;" src="@/static/svg/activity/bg-tab-start.svg"></image>
              <text style="z-index:1;">活动详情</text>
            </view>
            <view class="tab-item" :class="activeTab===1?'active':''" @click="activeTab=1">
              <image v-if="activeTab===1" mode="widthFix" class="absolute h-full" style="top:-8px;" src="@/static/svg/activity/bg-tab-end.svg"></image>
              <text style="z-index:1;">活动商品</text>
            </view>
          </view>
          <view class="tab-content">
            <activity-detail v-if="activeTab===0" :showTitle="false" :content="detailInfo.content" />
            <view v-if="activeTab===1" v-for="(goods,index) in detailInfo.activeGoods" :key="index" class="goods-item">
              <view class="flex justify-center">
                <view class="flex-col">
                  <text class="text-color-regular text-bold fs-14 mb-8">{{goods.goodsName}}</text>
                  <view class="flex" @click="showInstructionDialog(goods.id)">
                    <text class="fs-12 text-color-hint">可用商户&使用说明</text>
                    <image class="w-16 h-16" src="@/static/svg/activity/icon-more.svg"></image>
                  </view>
                </view>
              </view>
              <!-- 多商户不显示 -->
              <image v-if="goods.mulState===1" class="w-28 h-28" src="@/static/svg/activity/icon-goods-service.svg" @click="showServiceDialog(goods)"></image>
            </view>
          </view>
        </view>
        <view v-else class="mt-8 mb-16">
          <activity-detail :content="detailInfo.content" />
        </view>
      </view>
    </scroll-view>
    <scroll-view scroll-x="true" class="uni-bg-white">
      <view class="px-13 pt-13 pb-16 flex item-center flex-nowrap">
        <view v-if="[3,4].includes(detailInfo.activeState)" class="inline-flex center radius-8 px-16 py-4 fs-12 mr-8 text-color-hint uni-border whitespace-nowrap " @click="onActionClick('order')">订单管理</view>
        <view v-if="detailInfo.activeState===3" class="inline-flex center radius-8 px-16 py-4 fs-12 border-primary color-primary mr-8 whitespace-nowrap " @click="onActionClick('down')">下架</view>
        <view v-if="detailInfo.activeState!==3" class="inline-flex center radius-8 px-16 py-4 fs-12 border-primary color-primary mr-8 whitespace-nowrap " @click="onActionClick('delete')">删除</view>
        <view v-if="[1,2,3].includes(detailInfo.activeState)" class="inline-flex center radius-8 px-16 py-4 fs-12 border-secondary-warning color-secondary-warning mr-8 whitespace-nowrap " @click="onActionClick('edit')">修改</view>
        <view v-if="detailInfo.activeState===3" class="inline-flex center radius-8 px-16 py-4 fs-12 border-secondary-info color-secondary-info mr-8 whitespace-nowrap " @click="onActionClick('share')">
          <image class="size-16 mr-4" src="@/static/svg/icon-share-blue.svg"></image>分享
        </view>
        <view v-if="detailInfo.activeState===3" class="inline-flex center radius-8 px-16 py-4 fs-12 border-secondary-success color-secondary-success mr-8 whitespace-nowrap " @click="onActionClick('buy')">购买</view>
        <view class="inline-flex center radius-8 px-16 py-4 fs-12 mr-8 whitespace-nowrap color-secondary-success border-secondary-success" @click.stop="copyLink">
          <image class="size-16 mr-2" src="https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/link.png"></image>
          <text>复制链接</text>
        </view>
      </view>
      <view :style="`height:${safeAreaBottom}px;`"></view>
    </scroll-view>
    <template>
      <RedPacketDialog ref="redPacketDialog" :data="detailInfo.activeRedPacket" />
      <service-dialog :phoneNumber="detailInfo.activeMobile" :weixin="detailInfo.activeWechat" ref="serviceDialog" />
      <instructions-dialog ref="instructionDialog" />
      <OrderPopup ref="orderPopup" :data="detailInfo" />
    </template>
    <share-activity :id="detailInfo.id" :show="showSharePopup" @onClose="showSharePopup=false" />
  </view>
</template>

/**
 * 活动详情
 */
<script setup name="ActivityDetail">
import {
  onLoad,
  onShareAppMessage
} from '@dcloudio/uni-app'
import {
  ref,
  computed
} from 'vue'
import {
  useUserStore
} from '@/stores/modules/user.js'
import FullDiscountTag from '@/components/full-discount-tag/full-discount-tag.vue'
import RedPacketDialog from '@/pagesB/activity/components/red-packet-dialog.vue'
import ServiceDialog from '@/components/service-dialog/service-dialog.vue'
import OrderPopup from '@/pagesB/activity/components/order-popup.vue'
import ActivityDetail from '@/pagesB/activity/components/activity-detail/activity-detail.vue'
import PromotionInterest from '@/pagesB/activity/components/promotion-interest/promotion-interest.vue'
import Danmu from '@/pagesB/activity/components/danmu/danmu.vue'
// import UniNoticeBar from '@/pagesB/uni_modules/uni-notice-bar/components/uni-notice-bar/uni-notice-bar.vue'
import {
  activeDetailsApi,
  getCustomInfoApi,
  generateShortLinkApi
} from '@/api/activity.js'
import { businessActiveDeleteApi, businessActiveDownApi } from '@/api/business.js'
import {
  numberFormat,
  isVideoFile
} from '@/utils/index.js'
import { useActivity } from '@/hooks/useActivity.js'
const { isSignUp, isLink, photos, coverPicture, sortStepPrices, updateActivityInfo } = useActivity(detailInfo)

const userStore = useUserStore()
const navBar = ref(null)
const navBarHeight = computed(() => {
  const statusBarHeight = uni.getWindowInfo().statusBarHeight
  const navigationBarHeight = statusBarHeight + (navBar.value && navBar.value.height || 0)
  return navigationBarHeight
})
const safeAreaBottom = computed(() => {
  return uni.getSystemInfoSync().safeAreaInsets.bottom
})

const goBack = () => uni.navigateBack()

const swiperDotIndex = ref(0)
const swiperChange = (e) => {
  swiperDotIndex.value = e.detail.current
}

// 活动详情、活动商品Tab
const activeTab = ref(0)

// 领取红包状态：1-未领取，2-未使用，3-已使用
const redPacketDialog = ref(null)
const showRedPacket = () => {
  if (userStore.isLogin) {
    if (detailInfo.value.activeRedPacket.receiveState !== 3) {
      redPacketDialog.value.showDialog(true)
    }
  } else {
    console.log('detailinfo:', detailInfo.value);
    const url = detailInfo.value.promotionType === 'GROUP_BUY'
      ? `/pagesB/activity/activity-group-buy`
      : `/pagesB/activity/activity`;
    uni.navigateTo({
      url: `/pagesA/login/login?from=${encodeURIComponent(`${url}?id=${id.value}`)}`,
      events: {
        onLoginSuccess() {
          toRefresh()
        }
      }
    })
  }
}

const serviceDialog = ref(null)
const showServiceDialog = (goods) => {
  serviceDialog.value.showDialog(true, goods)
}

const instructionDialog = ref(null)
const showInstructionDialog = (activeGoodsId) => {
  instructionDialog.value.showDialog(true, activeGoodsId, 'activeGoodsId')
}

const orderPopup = ref(null)
const showOrderPopup = () => {
  orderPopup.value.show(true)
}

const showSharePopup = ref(false)

const onActionClick = (type) => {
  if (type === 'share') {
    showSharePopup.value = true
  } else if (type === 'buy') {
    if (isLink.value) {
      uni.navigateTo({
        url: `/pagesC/webview/webview?url=${detailInfo.value.activeUrl}`
      })
    } else {
      showOrderPopup()
    }
  } else if (type === 'signup') {
    showOrderPopup()
  } else if (type === 'down') {
    toShelf()
  } else if (type === 'delete') {
    toDelete()
  } else if (type === 'order') {
    uni.navigateTo({
      url: `/pagesB/my-activity/activity-order?id=${detailInfo.value.id}&_from=BActivityDetail`
    })
  } else if (type === 'edit') {
    uni.navigateTo({
      url: `/pagesG/publish/create-activity?id=${detailInfo.value.id}&from=myactivity`
    })
  }
}

const toShelf = () => {
  uni.showModal({
    content: '确定下架该活动？',
    success: (res) => {
      if (res.confirm) {
        businessActiveDownApi(detailInfo.value.id).then(res => {
          uni.showToast({
            title: '下架成功',
            icon: 'none'
          })
          getDetail()
        })

      }
    }
  })
}

const toDelete = () => {
  uni.showModal({
    content: '确定删除该活动？',
    success: (res) => {
      if (res.confirm) {
        businessActiveDeleteApi(detailInfo.value.id).then(res => {
          if (res) {
            uni.showToast({
              title: '删除成功',
              icon: 'none'
            })
            uni.$emit('deleteActivitySuccess', detailInfo.value.id)
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          }
        })
      }
    }
  })
}

const id = ref('')
const detailInfo = ref(undefined)

const getDetail = () => {
  activeDetailsApi(id.value).then(res => {
    detailInfo.value = res
    updateActivityInfo(res)
  }).catch(err => {
    uni.showToast({
      icon: 'none',
      title: err.message
    })
    if (err.code == 10014) {//链接失效
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/home/home'
        })
      }, 1000)
    }
  })
}

const toRefresh = () => {
  getDetail()
}

// TODO
const getCustomInfo = () => {
  getCustomInfoApi()
}

const copyLink = async () => {
  const url = detailInfo.value.promotionType === 'GROUP_BUY'
    ? `pagesB/activity/activity-group-buy?id=${detailInfo.value.id}`
    : `pagesB/activity/activity?id=${detailInfo.value.id}`;
  const data = await generateShortLinkApi({ 'pageUrl': url }).catch(err => null);
  if (!data) {
    uni.showToast({ title: '链接获取失败', icon: 'none' });
    return;
  }
  uni.setClipboardData({
    data,
    success: () => {
      // 先隐藏默认的
      uni.hideToast();
      // 再显示自己的
      uni.showToast({ title: '链接复制成功', icon: 'none' });
    },
  })
};

onLoad(options => {
  uni.hideShareMenu()
  console.log('活动详情', options)
  id.value = options.id
  getDetail()
})

onShareAppMessage((options) => {
  // console.log('活动详情分享', options,detailInfo.value)
  // if(options.form == 'button'){}
  console.log('options.target.dataset:', options.target.dataset)
  const url = detailInfo.value.promotionType === 'GROUP_BUY'
    ? `/pagesB/activity/activity-group-buy`
    : `/pagesB/activity/activity`;
  return {
    title: options.target.dataset.title,
    path: `${url}?id=${options.target.dataset.activityId}&code=${options.target.dataset.shareCode}&_from=BActivityDetail`,
    imageUrl: options.target.dataset.filepath
  }
})
</script>

<style lang="scss" scoped>
:root {
  .uni-noticebar {
    margin-bottom: 0;
  }
}

.page {
  position: relative;
  width: 100vw;
  height: 100vh;
}

.container {
  position: relative;
  display: flex;
  flex-direction: column;
}
.danmu {
  position: absolute;
  left: 16px;
  top: 114px;
}
.swiper-box {
  height: 320px;
  background-color: #000;
}

.swiper-item {
  height: 320px;
  position: relative;

  .notice-bar {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 36px;
  }
}

.swiper-stamp {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
}

.swiper-stamp-img {
  width: 160px;
  height: 160px;
}

.top {
  color: #fff;
}

.card {
  background-color: #fff;
  padding: 16px 12px;
  border-radius: 12px;
}

.price {
  color: #fa4543;
  font-size: 21px;
  font-style: normal;
  font-weight: 600;
  line-height: 22px;

  .symbol {
    color: #fa4543;
    font-size: 14px;
    font-style: normal;
    font-weight: 400;
    line-height: 22px;
  }
}

.old-price {
  color: rgba(51, 51, 51, 0.6);
  font-size: 14px;
  font-style: normal;
  font-weight: 500;
  line-height: 22px;
  text-decoration-line: line-through;

  .symbol {
    color: rgba(51, 51, 51, 0.6);
    font-weight: 400;
  }
}

.stoce {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  height: 20px;
  min-width: 64px;
  padding: 4px 0px;
  border-image-source: url('@/static/svg/activity/bg-stock.svg');
  border-image-slice: 0 8 0 8 fill;
  border-right: 8px solid;
  border-left: 8px solid;
  color: #fff;
  font-size: 10px;
  font-style: normal;
  font-weight: 400;
  line-height: normal;
}

.viewer-info {
  margin-top: 4px;
  color: rgba(51, 51, 51, 0.6);
  font-size: 12px;
  font-weight: 400;
}

.tabs {
  margin-top: 16px;
  display: flex;
  background-color: #f5f5f5;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;

  .tab-item {
    position: relative;
    height: 52px;
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    color: rgba(51, 51, 51, 0.6);
    font-size: 16px;
    font-weight: 500;
    line-height: 22px;

    &.active {
      color: #fa4543;
      font-size: 16px;
      font-style: normal;
      font-weight: 600;
      line-height: 22px;
    }
  }
}

.tab-content {
  background-color: #f5f5f5;
  padding: 18px 12px 10px;
  border-bottom-left-radius: 12px;
  border-bottom-right-radius: 12px;
}

.goods-item {
  display: flex;
  padding: 8px 12px;
  justify-content: space-between;
  align-items: center;
  border-radius: 8px;
  background: #fff;

  .img {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    margin-right: 12px;
  }

  &:not(:last-child) {
    margin-bottom: 8px;
  }
}
</style>
